import { ref, watch } from 'vue'
import { defineStore } from 'pinia'
import { permissionGetService } from '@/api/permission'

export const useUserStore = defineStore(
  'user',
  () => {
    const token = ref('')
    const setToken = (newToken) => {
      token.value = newToken;
    }
    const removeToken = () => {
      token.value = '';
    }
    const permissions = ref([]);
    const clearPermissions = () => {
      permissions.value = [];
    }
    const getPermissions = () => {
      return permissions.value;
    }
    const updatePermissions = async () => {
      if (permissions.value.length === 0) {
        try {
          const res = await permissionGetService();
          if (res.data.data) {
            permissions.value = res.data.data;
          }
        } catch (error) { }
      }
    }

    watch(
      token,
      (newToken) => {
        if (newToken) {
          updatePermissions()
        }
      }
    )


    return {
      token,
      setToken,
      removeToken,
      clearPermissions,
      getPermissions,
      updatePermissions
    }
  },
  {
    persist: true,
  },
)
